package com.neusoft.bizcore.schedule.converter;

import org.quartz.CalendarIntervalTrigger;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.schedule.dto.JobDetailDTO;
import com.neusoft.bizcore.schedule.dto.TriggerDTO;
import com.neusoft.bizcore.web.dto.AbstractConverter;

import lombok.extern.slf4j.Slf4j;

/**
 * description
 *
 * @author sunchf
 * @date 2018年12月26日 下午2:44:09
 */
@Slf4j
@Component
public class TriggerConverter extends AbstractConverter<Trigger, TriggerDTO> {

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    @Autowired
    private JobConverter jobConverter;

    @Override
    public Trigger toModel(TriggerDTO dto) {
        return null;
    }

    @Override
    public TriggerDTO toDTO(Trigger trigger, boolean forListView) {
        final TriggerDTO triggerDTO = new TriggerDTO();
        triggerDTO.setTriggerKey(trigger.getKey().toString());
        triggerDTO.setTriggerGroup(trigger.getKey().getGroup());
        triggerDTO.setTriggerName(trigger.getKey().getName());
        triggerDTO.setDescription(trigger.getDescription());
        triggerDTO.setPriority(trigger.getPriority());
        triggerDTO.setMayFireAgain(trigger.mayFireAgain());
        triggerDTO.setStartTime(trigger.getStartTime());
        triggerDTO.setEndTime(trigger.getEndTime());
        triggerDTO.setNextFireTime(trigger.getNextFireTime());
        triggerDTO.setPreviousFireTime(trigger.getPreviousFireTime());
        triggerDTO.setFinalFireTime(trigger.getFinalFireTime());

        final JobDetailDTO jobDetailDTO = this.jobConverter.toDTO(trigger.getJobKey());
        triggerDTO.setJobDetail(jobDetailDTO);

        try {
            triggerDTO.setTriggerState(
                    this.schedulerFactoryBean.getScheduler().getTriggerState(trigger.getKey()).toString());
        } catch (final SchedulerException e) {
            TriggerConverter.log.error("", e);
        }
        if (trigger instanceof CronTriggerImpl) {
            triggerDTO.setTriggerType("CronTrigger");
            final CronTriggerImpl newCronTrigger = (CronTriggerImpl) trigger;
            triggerDTO.setCronExpression(newCronTrigger.getCronExpression());
        }
        if (trigger instanceof CalendarIntervalTrigger) {
            triggerDTO.setTriggerType("SimpleTrigger");
            final CalendarIntervalTrigger newCronTrigger = (CalendarIntervalTrigger) trigger;
            triggerDTO.setRepeatInterval(newCronTrigger.getRepeatInterval());
        }
        return triggerDTO;
    }

}
